<template>
  <div style="width: 200px;">
    <el-menu
      default-active="1"
      class="el-menu-vertical-demo"
      :collapse="isCollapse"
      @open="handleOpen"
      @close="handleClose"
    >
      <el-sub-menu index="1">
        <template #title>
          <el-icon><location /></el-icon>
          <span>我的书单</span>
        </template>
        <el-menu-item-group>
          <template #title><span>我的</span></template>
          <el-menu-item index="1-1" @click="manageRecomment">管理书单</el-menu-item>
          <el-menu-item index="1-2" @click="manageUser">管理账户</el-menu-item>
          <el-menu-item index="1-3" @click="manageComments">新增图书</el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
      <el-menu-item index="2" @click="addbooklist">
        <el-icon><icon-menu /></el-icon>
        <template #title>添加书单</template>
      </el-menu-item>
      <el-menu-item index="3">
        <el-icon><setting /></el-icon>
        <template #title><span @click="logout()">退出登录</span></template>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { useUserStore } from '../plugins/pinia';
import { ElMessageBox, ElMessage } from 'element-plus';

const isCollapse = ref(false);
const userStore = useUserStore();
const userId = userStore.userInfo.id;

const { proxy } = getCurrentInstance();

// 判断是否登录
const checkLogin = async (callback) => {
  if (userId === 0) {
    // 提示用户登录
    try {
      await ElMessageBox.confirm(
        '请登录后再继续操作',
        '提示',
        {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      // 跳转到登录页面
      proxy.$router.push('/login'); 
    } catch {
      ElMessage.info('操作已取消');
    }
    return false; // 阻止后续事件
  }
  return true; // 用户已登录，可以继续
};

// 管理书单
const manageRecomment = async () => {
  if (await checkLogin()) {
    proxy.$emit('navigateToUserrecommend', userId);
  }
};

// 新增书单
const addbooklist = async () => {
  if (await checkLogin()) {
    proxy.$emit('navigateToNewrecommend');
  }
};

// 用户管理
const manageUser = async () => {
  if (await checkLogin()) {
    proxy.$emit('navigateToUser');
  }
};

// 管理评论
const manageComments = async () => {
  if (await checkLogin()) {
    proxy.$emit('navigateToNewbook');
  }
};

// 菜单打开事件
const handleOpen = (key, keyPath) => {
  console.log('Opened menu:', key, 'KeyPath:', keyPath);
};

// 菜单关闭事件
const handleClose = (key, keyPath) => {
  console.log('Closed menu:', key, 'KeyPath:', keyPath);
};

// 退出登录
const logout = () => {
  window.location.reload();
};
</script>

<style scoped>
/* 样式增强 */
.el-menu-vertical-demo {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.comment-item {
  padding: 10px 0;
}
</style>
